package bar.dark.lee.common;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import bar.dark.lee.R;

public class CalendarPickerDialog extends Dialog implements android.view.View.OnClickListener, OnTouchListener{

	ICalendarPickerDateSetListener dateSet;
	
	Context context;
	
	private ImageButton    pre,next;
	private ArrayList<BDTextView> tempList = new ArrayList<BDTextView>();
	
	private TextView    today,time;
	private TableLayout table;
	int     setYear;
	int     setMonth;
	int     setMonth2;
	int     setDay;
	
	private ArrayList<PositionClass> positionList = new ArrayList<PositionClass>();
	int tableLayoutWidth;
	int tableLayoutHeight;
	
	boolean firstRun = true;
	
	int colorSelect;
	
	private int toYear;
	private int toMonth;
	private int toDate;
	
	public CalendarPickerDialog(Context ctx, ICalendarPickerDateSetListener listener, int year, int month, int date) {
		
		super(ctx);
		
		context = ctx;
		
		toYear = year;
		toMonth = month;
		toDate = date;
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.calendar_picker_activity);
		
		((LinearLayout)findViewById(R.id.calendar_picker_back)).setBackgroundColor(context.getResources().getColor(R.color.accountBookColor));
		
		dateSet = listener;
		
		pre = (ImageButton) findViewById(R.id.calendar_picker_pre);
		next = (ImageButton) findViewById(R.id.calendar_picker_next);
		today = (TextView) findViewById(R.id.calendar_picker_today);
		time = (TextView) findViewById(R.id.calendar_picker_time);
		Calendar calendar = Calendar.getInstance();
		setYear = year;;
		setMonth = month;
		setMonth2 = calendar.get(Calendar.MONTH) + 1;
		setDay = date;
		time.setText("오늘은  " + calendar.get(Calendar.YEAR) + "년  " + (calendar.get(Calendar.MONTH)+1) + "월  " + calendar.get(Calendar.DAY_OF_MONTH)
				+ "일 입니다.");
		
		table = (TableLayout) findViewById(R.id.calendar_picker_table);
		for (int i = 0; i < 6; i++) 
		{
			TableRow tr = new TableRow(context);
			
			for (int j = 0; j < 7; j++) 
			{
				BDTextView tv = new BDTextView(context);
				
				if (j == 0) 
				{
					tv.setTextColor(Color.RED);
					tv.setTextSize(20);
				} 
				else if (j == 6) 
				{
					tv.setTextColor(Color.BLUE);
					tv.setTextSize(20);
				} 
				else 
				{
					tv.setTextColor(Color.BLACK);
					tv.setTextSize(20);
				}
				
				tv.setMinimumHeight(BDUtil.dipToPixel(context, 45));
				tv.setGravity(Gravity.CENTER);
				tr.addView(tv);
				tempList.add(tv);
				tv.setOnClickListener(CalendarPickerDialog.this);
				//tv.setOnTouchListener(this);
				
			}
			
			table.addView(tr);
		}

		table.setStretchAllColumns(true);
		findViewById(R.id.calendar_picker_frame).setOnTouchListener(CalendarPickerDialog.this);
		View view = new View(context);
		view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		view.setOnTouchListener(CalendarPickerDialog.this);
		((FrameLayout)findViewById(R.id.calendar_picker_frame)).addView(view);

		setCalendar(toYear, toMonth);

		pre.setOnClickListener(CalendarPickerDialog.this);
		next.setOnClickListener(CalendarPickerDialog.this);
		
		today.setOnClickListener(CalendarPickerDialog.this);
		
		colorSelect = context.getResources().getColor(R.color.selectCalendar);
	}
	
	public interface ICalendarPickerDateSetListener {
		abstract public void onDateSet(int year, int monthOfYear, int dayOfMonth);
	}
	
	private void setCalendar(int year, int month) 
	{
		
		for (int i = 0; i < tempList.size(); i++)
		{
			BDTextView tv = (BDTextView) tempList.get(i);
			tv.setBackgroundColor(0);
			tv.setPaintFlags(tv.getPaintFlags() &~ Paint.UNDERLINE_TEXT_FLAG);
			tv.setText("");
		}
		
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR, year);
		calendar.set(Calendar.MONTH, month);
		calendar.set(Calendar.DAY_OF_MONTH, 1);

		today.setText(year + "년 " + (month + 1) + "월");

		int getDay = calendar.get(Calendar.DAY_OF_WEEK);

		int j = 1;
		
		for (int i = getDay - 1; i < calendar
				.getActualMaximum(Calendar.DAY_OF_MONTH) + getDay - 1; i++) 
		{
			BDTextView tv = tempList.get(i);
			
			if (j == toDate) 
			{
				if ((setYear == toYear) && (setMonth == toMonth)) 
				{
					tv.setPaintFlags(tv.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
				}
				
				tv.setText(j + "");
				
			}
			else 
			{
				tv.setText(j + "");
			}
			
			j++;
		}
		
		firstRun = true;
	}
	
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.calendar_picker_pre) 
		{
			setMonth--;
			
			if (setMonth < 0) 
			{
				setYear--;
				setMonth = 11;
			}
			
			setCalendar(setYear, setMonth);
		} 
		else if (v.getId() == R.id.calendar_picker_next) 
		{
			setMonth++;
			
			if (setMonth > 11) 
			{
				setMonth = 0;
				setYear++;
			}
			
			setCalendar(setYear, setMonth);
		} 
		else if(v.getId() == R.id.calendar_picker_today)
		{
			dismiss();
			
			DatePickerDialog dpd = new DatePickerDialog(context, new OnDateSetListener()
			{
				@Override
				public void onDateSet(DatePicker view, int year, int monthOfYear,
						int dayOfMonth)
				{
					dateSet.onDateSet(year, monthOfYear, dayOfMonth);
				}
			}, toYear, toMonth, toDate);
			
			dpd.show();
		}
	}

	private class PositionClass {
		
		private int left;
		private int top;
		private int right;
		private int bottom;
			
		public PositionClass(int left, int right, int top, int bottom) {
			this.left = left;
			this.top = top;
			this.right = right;
			this.bottom = bottom;
		}

		public int getLeft() {
			return left;
		}

		public void setLeft(int left) {
			this.left = left;
		}

		public int getTop() {
			return top;
		}

		public void setTop(int top) {
			this.top = top;
		}

		public int getRight() {
			return right;
		}

		public void setRight(int right) {
			this.right = right;
		}

		public int getBottom() {
			return bottom;
		}

		public void setBottom(int bottom) {
			this.bottom = bottom;
		}
	}

	int changedIndex = -1;

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		
		if (firstRun) 
		{
			positionList.clear();
			
			for (int i=0; i < tempList.size(); i++) 
			{
				TextView tv = tempList.get(i);
				
				positionList.add(new PositionClass(tv.getLeft(), tv.getRight(), ((View)tv.getParent()).getTop(), ((View)tv.getParent()).getBottom()));
			}
			
			firstRun = false;
		}
		
		final int action = event.getAction();
		
		if (action == MotionEvent.ACTION_DOWN)
		{
			final float x = event.getX();
	        final float y = event.getY();
	        
	        String selectDate = "";
	        
			for (int i=0; i < positionList.size(); i++) 
	        {
				TextView view = tempList.get(i);
				
				if (view.getText().toString().equals(""))
				{
					continue;
				}
	        	
	        	PositionClass position = positionList.get(i);
	        	
	        	if (position.getLeft() < x && x < position.getRight() && position.getTop() < y && y <position.getBottom()) {
	        		
					view.buildDrawingCache();
					Bitmap bitmap = view.getDrawingCache();
					int color = bitmap.getPixel(0, 0);
					view.destroyDrawingCache();
					
	        		if (color == 0)
	        		{
	        			tempList.get(i).setBackgroundColor(colorSelect);
	        		}
	        		
	        		selectDate = tempList.get(i).getText().toString();
	        	}
	        }
			
			if (!selectDate.equals(""))
			{
				dateSet.onDateSet(setYear, setMonth, Integer.parseInt(selectDate));
				dismiss();
			}
	    }

		return true;
	}
	
}
